package com.example.canvasdemo.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.canvasdemo.R
import com.example.canvasdemo.model.ChatMessage
import com.example.canvasdemo.model.UserModel
import com.example.canvasdemo.network.ApiService
import com.example.canvasdemo.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class ChatMessageAdapter(
    private val chatMessages: MutableList<ChatMessage>
) : RecyclerView.Adapter<ChatMessageAdapter.ChatMessageViewHolder>() {

    // 缓存用户名
    private val userCache = mutableMapOf<Long, String>()
    private val apiService = RetrofitClient.instance.create(ApiService::class.java)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatMessageViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_chat_message, parent, false)
        return ChatMessageViewHolder(view)
    }

    override fun onBindViewHolder(holder: ChatMessageViewHolder, position: Int) {
        val chatMessage = chatMessages[position]
        holder.bind(chatMessage)
    }

    override fun getItemCount(): Int = chatMessages.size

    fun updateMessages(newMessages: List<ChatMessage>) {
        chatMessages.clear()
        chatMessages.addAll(newMessages)
        notifyDataSetChanged()
    }

    inner class ChatMessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val tvUserName: TextView = itemView.findViewById(R.id.tvUserName)
        private val tvMessage: TextView = itemView.findViewById(R.id.tvMessage)
        private val tvTime: TextView = itemView.findViewById(R.id.tvTime)

        fun bind(chatMessage: ChatMessage) {
            // 从缓存中获取用户名，若没有则发起请求
            val userName = userCache[chatMessage.userId]

            if (userName != null) {
                tvUserName.text = "用户名: $userName"
            } else {
                fetchUserName(chatMessage.userId, tvUserName)
            }

            tvMessage.text = chatMessage.message
            tvTime.text = chatMessage.createTime
        }

        private fun fetchUserName(userId: Long, userNameTextView: TextView) {
            apiService.getUserById(userId).enqueue(object : Callback<UserModel> {
                override fun onResponse(call: Call<UserModel>, response: Response<UserModel>) {
                    if (response.isSuccessful) {
                        val user = response.body()
                        user?.let {
                            userCache[userId] = it.username
                            userNameTextView.text = "用户名: ${it.username}"
                        }
                    } else {
                        userNameTextView.text = "用户名加载失败"
                    }
                }

                override fun onFailure(call: Call<UserModel>, t: Throwable) {
                    userNameTextView.text = "用户名加载失败"
                }
            })
        }
    }
}

